package com.chatsystem.controller;

import com.chatsystem.dto.ApiResponse;
import com.chatsystem.dto.MessageRequest;
import com.chatsystem.entity.Message;
import com.chatsystem.service.MessageService;
import com.chatsystem.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 消息控制器
 * 
 * @author ChatSystem
 * @version 1.0.0
 */
@RestController
@RequestMapping("/messages")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class MessageController {

    private final MessageService messageService;
    private final UserService userService;

    /**
     * 发送消息
     * 
     * @param request 消息请求
     * @param username 发送者用户名
     * @return 发送结果
     */
    @PostMapping("/send")
    public ResponseEntity<ApiResponse<?>> sendMessage(@Valid @RequestBody MessageRequest request, 
                                                     @RequestParam String username) {
        try {
            var senderOpt = userService.findByUsername(username);
            if (senderOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("发送者不存在"));
            }

            var sender = senderOpt.get();
            var message = messageService.sendMessage(
                sender.getId(), 
                request.getReceiverId(), 
                request.getContent(), 
                Message.MessageType.valueOf(request.getMessageType()),
                null, null, null
            );

            return ResponseEntity.ok(ApiResponse.success("消息发送成功", message));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取两个用户之间的消息记录
     * 
     * @param otherUserId 对方用户ID
     * @param username 当前用户名
     * @param page 页码
     * @param size 每页大小
     * @return 消息记录
     */
    @GetMapping("/chat/{otherUserId}")
    public ResponseEntity<ApiResponse<?>> getChatMessages(@PathVariable Long otherUserId,
                                                         @RequestParam String username,
                                                         @RequestParam(defaultValue = "0") int page,
                                                         @RequestParam(defaultValue = "20") int size) {
        try {
            var currentUserOpt = userService.findByUsername(username);
            if (currentUserOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            var currentUser = currentUserOpt.get();
            Page<Message> messages = messageService.getMessagesBetweenUsers(
                currentUser.getId(), otherUserId, page, size
            );

            return ResponseEntity.ok(ApiResponse.success(messages));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取未读消息
     * 
     * @param username 用户名
     * @return 未读消息列表
     */
    @GetMapping("/unread")
    public ResponseEntity<ApiResponse<?>> getUnreadMessages(@RequestParam String username) {
        try {
            var userOpt = userService.findByUsername(username);
            if (userOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            var user = userOpt.get();
            var messages = messageService.getUnreadMessages(user.getId());

            return ResponseEntity.ok(ApiResponse.success(messages));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 标记消息为已读
     * 
     * @param messageId 消息ID
     * @return 操作结果
     */
    @PutMapping("/{messageId}/read")
    public ResponseEntity<ApiResponse<?>> markAsRead(@PathVariable Long messageId) {
        try {
            var message = messageService.markAsRead(messageId);
            return ResponseEntity.ok(ApiResponse.success("消息已标记为已读", message));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 撤回消息
     * 
     * @param messageId 消息ID
     * @param username 用户名
     * @return 操作结果
     */
    @PutMapping("/{messageId}/recall")
    public ResponseEntity<ApiResponse<?>> recallMessage(@PathVariable Long messageId,
                                                       @RequestParam String username) {
        try {
            var userOpt = userService.findByUsername(username);
            if (userOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            var user = userOpt.get();
            boolean success = messageService.recallMessage(messageId, user.getId());

            if (success) {
                return ResponseEntity.ok(ApiResponse.success("消息撤回成功"));
            } else {
                return ResponseEntity.badRequest().body(ApiResponse.error("消息撤回失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取可撤回的消息列表
     * 
     * @param username 用户名
     * @return 可撤回的消息列表
     */
    @GetMapping("/recallable")
    public ResponseEntity<ApiResponse<?>> getRecallableMessages(@RequestParam String username) {
        try {
            var userOpt = userService.findByUsername(username);
            if (userOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            var user = userOpt.get();
            var messages = messageService.getRecallableMessages(user.getId());

            return ResponseEntity.ok(ApiResponse.success(messages));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 统计未读消息数量
     * 
     * @param username 用户名
     * @return 未读消息数量
     */
    @GetMapping("/unread/count")
    public ResponseEntity<ApiResponse<?>> countUnreadMessages(@RequestParam String username) {
        try {
            var userOpt = userService.findByUsername(username);
            if (userOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
            }

            var user = userOpt.get();
            long count = messageService.countUnreadMessages(user.getId());

            return ResponseEntity.ok(ApiResponse.success(count));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
} 